/*
 * @Description: 电子文件移交归档列表
 * @Author: Rfan
 * @Date: 2022-11-19 16:31:39
 * @LastEditTime: 2022-12-08 16:22:23
 */

import { useEffect, useMemo, useState } from 'react';
import { Button, Space, Table } from 'antd';
import classNames from 'classnames/bind';
import { formatDate } from '@/utils';
import { useFormatMessage } from '@/utils/intlHelpers';
import { useArchivingContext } from '../contexts/ArchivingContext';
import EditArchivingDialog from './dialogs/EditArchivingDialog';
import type { IRegArchivingListParams } from '@/api/registration/archiving';
import type { IRegArchivingItem } from '@/interfaces/registration';
import type { ColumnsType } from 'antd/es/table';
import type { IPageQuery } from '@/interfaces/global';
import styles from '../styles/pageList.module.scss';

const cx = classNames.bind(styles);

const PageList = (props: any) => {
  const { className } = props;
  const {
    list,
    selectItems,
    setSelectKey,
    getRegArchivingList,
    deleteItem,
    archivingFilter,
    resultFilter
  } = useArchivingContext();
  const formatMessage = useFormatMessage();

  const [loading, setLoading] = useState(false);
  const [total, setTotal] = useState(0);
  const [listQuery, setListQuery] = useState<IPageQuery<IRegArchivingListParams>>({
    pageNo: 1,
    pageSize: 10,
    param: {}
  });
  // 加入鉴定批次弹窗可视状态
  const [editVisible, setEditVisible] = useState(false);
  // 选中内容
  const [selectData, setSelectData] = useState<IRegArchivingItem>(null);

  useEffect(() => {
    if (listQuery && listQuery.param) {
      setLoading(true);
      getRegArchivingList(listQuery)
        .then((res: any) => {
          setTotal(res?.totalCount);
        })
        .finally(() => {
          setLoading(false);
        });
    }
  }, [listQuery]);

  /**
   * @description 切换页码触发
   * @param {number} page 页码
   * @param {number} pageSize 每页条目数
   */
  const pageChange = (page: number, pageSize: number) => {
    setListQuery((state) => ({
      ...state,
      pageNo: page,
      pageSize
    }));
  };

  /**
   * @description : 表格选项相关设置
   * @param {number} selectedRowKeys 选择的项目的KEY
   */
  const onSelectChange = (selectedRowKeys: number[]) => {
    setSelectKey(selectedRowKeys);
  };

  /**
   * @description:  表格多选配置
   */
  const rowSelection = {
    selectItems,
    onChange: onSelectChange
  };

  const editItem = (item: any) => {
    setSelectData(item);
    setEditVisible(true);
  };

  const columns: ColumnsType<IRegArchivingItem> = [
    { title: '序号', dataIndex: 'id', key: 'id' },
    {
      title: '登记时间',
      dataIndex: 'registrationTime',
      key: 'registrationTime',
      render: (time: number) => formatDate(time)
    },
    { title: '电子档案形成单位', key: 'genUnit' },
    {
      title: '归档时间',
      dataIndex: 'archivingTime',
      key: 'archivingTime',
      render: (time: number) => formatDate(time)
    },
    { title: '全宗', dataIndex: 'fondsName', key: 'fondsName' },
    { title: '档案类型', dataIndex: 'archiveTypeName', key: 'archiveTypeName' },
    { title: '分类', dataIndex: 'category', key: 'category' },
    { title: '归档电子文件门类', key: 'archiveClass' },
    { title: '形成年度', dataIndex: 'year', key: 'year' },
    { title: '保管期限', key: 'period' },
    { title: '卷数', dataIndex: 'folderCount', key: 'folderCount' },
    { title: '件数', dataIndex: 'fileCount', key: 'fileCount' },
    { title: '电子文件数', key: 'eRecordCount' },
    { title: '张数', dataIndex: 'pageCount', key: 'pageCount' },
    { title: '分钟', dataIndex: 'duration', key: 'duration' },
    { title: '字节数', key: 'id' },
    {
      title: '归档方式',
      dataIndex: 'archivingMode',
      key: 'archivingMode',
      render: (val: string) => archivingFilter(parseInt(val, 10))
    },
    { title: '检测ID', dataIndex: 'detectionJobId', key: 'detectionJobId' },
    {
      title: '检测结果',
      dataIndex: 'detectionResult',
      key: 'detectionResult',
      render: (val) => resultFilter(val)
    },
    {
      title: formatMessage('tableAction'),
      key: 'action',
      className: cx('action-col'),
      render: (_text: any, record: any) => (
        <Space>
          <Button
            type="link"
            size="small"
            onClick={() => {
              editItem(record);
            }}
          >
            编辑
          </Button>
          <Button
            type="link"
            size="small"
            onClick={() => {
              deleteItem(record.id);
            }}
          >
            删除
          </Button>
        </Space>
      )
    }
  ];

  return (
    <div className={className}>
      <Table
        columns={columns}
        dataSource={list}
        loading={loading}
        rowKey="id"
        bordered
        rowSelection={rowSelection}
        pagination={{
          current: listQuery.pageNo,
          pageSize: listQuery.pageSize,
          total,
          onChange: pageChange
        }}
      />

      {useMemo(
        () =>
          selectData && (
            <EditArchivingDialog
              visible={editVisible}
              data={selectData}
              onClose={() => {
                setEditVisible(false);
              }}
            />
          ),
        [editVisible]
      )}
    </div>
  );
};

export default PageList;
